package com.wenhao.leetcode.medium;

import com.wenhao.leetcode.structure.ListNode;

/**
 * 题目：https://leetcode-cn.com/problems/rotate-list/
 * 旋转链表
 * @author Wenhao Tong
 * @create 2021-07-12 0:11
 */
public class LeetCode61 {
    public static void main(String[] args) {

    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode ahead = head;
        int length = 1;
        while (ahead.next != null) {
            ahead = ahead.next;
            length++;
        }
        k = k % length;
        ahead = head;
        ListNode behind = head;
        for (int i = 0;i < k;i++) {
            ahead = ahead.next;
        }
        while (ahead.next != null) {
            ahead = ahead.next;
            behind = behind.next;
        }
        // 细节 如果移动的是0位的话，那么ahead和behind都是最后一个节点，所以要先把next指向head，不然就会返回一个null了
        // 只要不是移动0位，behind的next都不会是null
        ahead.next = head;
        ListNode newHead = behind.next;
        behind.next = null;
        return newHead;
    }

}
